<?php
namespace controllers;
use system\Container;
use system\MyError;
use system\Route\Route;

class HomeBase extends Common {
	/**
	 * HomeBase constructor.
	 */
	public function __construct() {
		parent::__construct();
		self::setConfig();
	}

	/**
	 * 调用Api
	 * @param string $name 	将要调用的模块接口
	 * @param array $args	接口所需参数
	 * @author Colin <amcolin@126.com>
	 * @date 2022-01-22 下午4:21
	 * @return array|string
	 * @throws
	 */
	public function callApi($name = '' , $args = []){
		list($module , $url) = explode(':' , $name);
		if(!addonIs($module)){
			throw new MyError('模块不存在或未安装【' . $module . '】');
		}
		$explode = explode('/' , $url);
		$method = array_pop($explode);
		$action = array_pop($explode);
		if (count($explode) > 0){
			// 还有，则是多目录
			$action = implode('\\' , $explode);
		}
		$action = 'addons\\' . $module . '\\controllers\\' . $action;
		try {
			$res = Route::execController($action , $method , $args);
			header_remove('content-type');
			return json_decode($res , true);
		}catch (\ReflectionException $e){
			return error($e->getMessage());
		}
	}

	/**
	 * 注入模板公共数据
	 * @throws MyError
	 * @author Colin <amcolin@126.com>
	 * @date 2022-01-26 上午10:35
	 */
	protected function assignBaseData(){
		// 模拟接口请求
		$navs = $this->callApi('navigation:api/getNavs');
		self::assign('navs' , $navs['data']);
		// 获取logo
		$logo = envg('logo');
		$contacts = envg('contacts');
		$copyright = envg('copyright');
		self::assign('config' , [
			'logo' => $logo ,
			'contacts' => $contacts ,
			'copyright' => $copyright
		]);
	}

	/**
	 * 封装渲染方法
	 * @param string $file
	 * @return string
	 * @throws MyError
	 * @author Colin <amcolin@126.com>
	 * @date 2022-01-26 上午10:36
	 */
	protected function render($file = ''){
		$this->assignBaseData();
		return self::view($file);
	}
}